from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action, api_view, permission_classes
from rest_framework.response import Response
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
from django.shortcuts import get_object_or_404
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.conf import settings
from django.db import transaction
import base64
import uuid
import os
import secrets
import string
from .models import TravelRecord, Comment, Like
from .serializers import (
    TravelRecordSerializer, CommentSerializer, 
    LikeSerializer, UserSerializer
)

class TravelRecordViewSet(viewsets.ModelViewSet):
    """旅游记录视图集"""
    queryset = TravelRecord.objects.all()
    serializer_class = TravelRecordSerializer
    permission_classes = [permissions.AllowAny]  # 默认允许所有访问
    
    def get_permissions(self):
        """为写操作单独设置权限"""
        if self.action in ['create', 'update', 'partial_update', 'destroy', 'like', 'add_comment', 'delete_image']:
            return [permissions.IsAuthenticated()]
        return [permissions.AllowAny()]

    def get_queryset(self):
        queryset = TravelRecord.objects.all()
        # 支持按用户筛选
        user_id = self.request.query_params.get('user_id')
        if user_id:
            queryset = queryset.filter(user_id=user_id)
        return queryset

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

    def perform_destroy(self, instance):
        """删除旅游记录时同时删除关联的图片文件"""
        # 删除所有关联的图片文件
        for image_url in instance.images:
            if image_url.startswith('https://'):
                try:
                    # 提取文件路径
                    file_path = image_url.split('/media/')[1]
                    if default_storage.exists(file_path):
                        default_storage.delete(file_path)
                        print(f"Deleted image file: {file_path}")
                except (IndexError, Exception) as e:
                    print(f"Error deleting image {image_url}: {str(e)}")
        
        # 删除数据库记录
        instance.delete()

    @action(detail=True, methods=['get'])
    def comments(self, request, pk=None):
        """获取特定旅游记录的所有评论"""
        travel_record = self.get_object()
        comments = travel_record.comments.all()
        serializer = CommentSerializer(comments, many=True)
        return Response(serializer.data)

    @action(detail=True, methods=['post'])
    def add_comment(self, request, pk=None):
        """为旅游记录添加评论"""
        travel_record = self.get_object()
        serializer = CommentSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            serializer.save(travel_record=travel_record)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=True, methods=['post'])
    def like(self, request, pk=None):
        """点赞旅游记录"""
        travel_record = self.get_object()
        like, created = Like.objects.get_or_create(
            user=request.user,
            travel_record=travel_record
        )
        if not created:
            like.delete()
            return Response({'status': 'unliked'})
        return Response({'status': 'liked'})

    @action(detail=True, methods=['get'])
    def likes(self, request, pk=None):
        """获取旅游记录的点赞列表"""
        travel_record = self.get_object()
        likes = travel_record.likes.all()
        serializer = LikeSerializer(likes, many=True)
        return Response(serializer.data)


    @action(detail=True, methods=['post'])
    @transaction.atomic
    def delete_image(self, request, pk=None):
        """删除图片（事务保护）"""
        travel_record = self.get_object()
        image_url = request.data.get('image_url')
        
        if not image_url:
            return Response({'error': '没有提供图片URL'}, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            # 从图片列表中移除
            if image_url in travel_record.images:
                travel_record.images.remove(image_url)
                travel_record.save()
                
                # 从存储中删除物理文件
                if image_url.startswith('https://'):
                    # 提取文件路径
                    file_path = image_url.split('/media/')[1]
                    if default_storage.exists(file_path):
                        default_storage.delete(file_path)
                
                return Response({'status': '图片删除成功'}, status=status.HTTP_200_OK)
            else:
                return Response({'error': '图片不存在'}, status=status.HTTP_404_NOT_FOUND)
                
        except Exception as e:
            # 事务会自动回滚
            return Response({'error': f'图片删除失败: {str(e)}'}, status=status.HTTP_400_BAD_REQUEST)

class CommentViewSet(viewsets.ModelViewSet):
    """评论视图集"""
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer
    permission_classes = [permissions.AllowAny]  # 默认允许所有访问
    
    def get_permissions(self):
        """为写操作单独设置权限"""
        if self.action in ['create', 'update', 'partial_update', 'destroy']:
            return [permissions.IsAuthenticated()]
        return [permissions.AllowAny()]

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

class LikeViewSet(viewsets.ModelViewSet):
    """点赞视图集"""
    queryset = Like.objects.all()
    serializer_class = LikeSerializer
    permission_classes = [permissions.IsAuthenticated]

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

class UserViewSet(viewsets.ReadOnlyModelViewSet):
    """用户视图集（只读）"""
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [permissions.AllowAny]

@api_view(['POST'])
@permission_classes([permissions.AllowAny])
def wechat_login(request):
    """微信小程序登录"""
    code = request.data.get('code')
    
    if not code:
        return Response({'error': '缺少code参数'}, status=status.HTTP_400_BAD_REQUEST)
    
    # 这里应该调用微信API获取openid，这里简化处理
    # 实际项目中需要: 
    # 1. 调用微信 auth.code2Session API
    # 2. 根据openid获取或创建用户
    
    # 简化版：使用code作为用户名创建用户
    username = f'wechat_{code}'
    # 生成随机密码
    alphabet = string.ascii_letters + string.digits + string.punctuation
    random_password = ''.join(secrets.choice(alphabet) for i in range(12))
    
    user, created = User.objects.get_or_create(
        username=username,
        defaults={'password': make_password(random_password)}
    )
    
    # 生成JWT token
    refresh = RefreshToken.for_user(user)
    
    return Response({
        'refresh': str(refresh),
        'access': str(refresh.access_token),
        'user_id': user.id,
        'username': user.username
    })
